package com.example.demo.controller;


import com.example.demo.model.Assignment;
import com.example.demo.security.CustomUserDetails;
import com.example.demo.service.AssignmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/teacher/assignments")
@RequiredArgsConstructor
public class TeacherAssignmentController {
    private final AssignmentService assignmentService;

    // 获取课程所有作业
    @GetMapping("/course/{courseId}")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<List<Assignment>> getCourseAssignments(
            @PathVariable Long courseId) {
        return ResponseEntity.ok(assignmentService.getAssignmentsByCourse(courseId));
    }

    // 获取作业的所有学生提交
    @GetMapping("/{assignmentId}/submissions")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<List<Objects>> getAssignmentSubmissions(
            @PathVariable Long assignmentId) {
        return ResponseEntity.ok(assignmentService.getAssignmentSubmissions(assignmentId));
    }

    // 批改作业
    @PutMapping("/submissions/{submissionId}/grade")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> gradeAssignment(
            @PathVariable Long submissionId,
            @RequestBody GradeAssignment grade) {
        assignmentService.gradeAssignment(submissionId, grade);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{assignmentId}/statistics")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<AssignmentStatistics> getAssignmentStatistics(
            @PathVariable Long assignmentId,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        Long teacherId = userDetails.getId();
        return ResponseEntity.ok(assignmentService.getAssignmentStatistics(assignmentId, teacherId));
    }

    @PostMapping("/{assignmentId}/bulk-grade")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> bulkGradeAssignments(
            @PathVariable Long assignmentId,
            @RequestBody List<BulkGrade> grades,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        Long teacherId = userDetails.getId();
        assignmentService.bulkGradeAssignments(assignmentId, grades, teacherId);
        return ResponseEntity.ok().build();
    }
}